package com.example.demo.gateway.event;

import com.example.demo.gateway.entity.GatewayUpstream;
import com.example.demo.gateway.filter.UpstreamReactorLoadBalancer;
import com.example.demo.gateway.repository.GatewayUpstreamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//自定义事件监听器
@Component
public class RefreshUpstreamEventListener implements ApplicationListener<RefreshUpstreamEvent> {

    @Autowired
    private GatewayUpstreamRepository repository;
    @Autowired
    private UpstreamReactorLoadBalancer loadBalancer;

    @Override
    public void onApplicationEvent(RefreshUpstreamEvent event) {
        Map<String, List<GatewayUpstream>> map = repository.findAll()
                .toStream()
                .collect(Collectors.groupingBy(GatewayUpstream::getServiceId));
        loadBalancer.refresh(map);

    }
}